document.getElementById('captchaImg').addEventListener('click', getCaptcha);

function getCaptcha() {
    fetch("/erb/api/auth/captcha.png", {
        method: "GET",
        credentials: "include"
    }).then(response => {
        if (response.ok) {
            // 返回图片输出流
            return response.blob();
        } else {
            showAlert("获取验证码失败", "error", 3000)
            return false;
        }
    }).then(blob  => {
        if (blob instanceof Blob) {
            let imgDiv = document.getElementById("captchaImg");
            imgDiv.innerHTML = "";
            let img = document.createElement("img");
            imgDiv.appendChild(img);
            const url = URL.createObjectURL(blob);
            img.onload = () => URL.revokeObjectURL(url);
            img.src = url;
        }
    }).catch(error => {
        showAlert("获取验证码失败", "error", 3000)
        console.log(error);
    })
}

function register() {
    let jsonData = {
        "username": document.getElementById("username").value,
        "password": document.getElementById("password").value,
        "email": document.getElementById("email").value,
        "verificationEmailCode": document.getElementById("emailCode").value,
        "verificationCode": document.getElementById("captcha").value
    }
    fetch("/erb/api/auth/register", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(jsonData),
        credentials: "include"
    }).then(response => {
        if (response.status === 200) {
            return response.json();
        } else {
            showAlert("注册失败", "error", 3000)
        }
    }).then(data => {
        if (data.status) {
            showAlert("注册成功, 即将跳转到登录页面", "success", 3000);
            setTimeout(() => {
                window.location.href = "/erb/page/auth/login";
            }, 3000);
        } else {
            showAlert(data.message, "error", 3000);
            console.log(data.message);
        }
    }).catch(error => {
        showAlert("注册失败", "error", 3000)
    })
}

document.addEventListener("DOMContentLoaded", getCaptcha);